package xx.iverson.service.impl;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import xx.iverson.dto.request.SyUserRequestDto;
import xx.iverson.enums.EnumException;
import xx.iverson.exception.BusinessException;
import xx.iverson.result.ReturnResult;
import xx.iverson.service.SyAuthService;
import xx.iverson.util.SequenceGenUtil;

import java.util.concurrent.TimeUnit;

/**
 * xx.iverson.service.impl.SyAuthServiceImpl
 * 描述：鉴权服务实现类
 * on 2025/7/1-上午10:51
 *
 * @author weijx
 */
@Service
public class SyAuthServiceImpl implements SyAuthService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Value("${app.token.expire}")
    private long tokenExpireSeconds;

    @Override
    public ReturnResult<?> generateAndStoreToken(SyUserRequestDto requestDto) {
        // 生成唯一 Token（可以用UUID或JWT生成，但不依赖JWT验证）
        String token = SequenceGenUtil.getKey();

        // 存入 Redis，并设置过期时间
        String redisKey = "auth:token:" + token;
        redisTemplate.opsForValue().set(redisKey, requestDto.getUsername());
        redisTemplate.expire(redisKey, tokenExpireSeconds, TimeUnit.SECONDS);
        return ReturnResult.success("生成并保存 Token 成功", token);
    }

    @Override
    public ReturnResult<?> verifyToken(String token) {
        String redisKey = "auth:token:" + token;
        boolean exists = Boolean.TRUE.equals(redisTemplate.hasKey(redisKey));
        if (!exists) {
            throw new BusinessException(EnumException.USER_NOT_LOGIN);
        }
        return ReturnResult.success("验证 Token 成功", true);
    }

    @Override
    public ReturnResult<?> invalidateToken(String token) {
        String redisKey = "auth:token:" + token;
        redisTemplate.delete(redisKey);
        return ReturnResult.success("删除 Token 成功", true);
    }
}
